package main

import (
	"net/http"
	"global/core"
	"strings"
	"fmt"
	"global/libs/http/app"
	"github.com/ngaut/log"
	"global/util"
	"global/model"
	"strconv"
	"github.com/shopspring/decimal"
)

type HandleCoinDetail struct {
	BaseHandler
	ctx 		*core.Context
	symbol 		string
}

func (h *HandleCoinDetail) Construct(ctx *core.Context)  {
	h.ctx = ctx
}

func (h *Handler) OnHandleGetCoinDetail(writer http.ResponseWriter, request *http.Request)  {
	h.writer = writer
	symbol := strings.ToLower(request.FormValue("symbol"))
	uid, _ := strconv.Atoi(request.FormValue("uid"))
	if symbol == "" {
		h.Error(app.ErrParameter)
		return
	}

	d, ErrorCode := h.getCoinDetailData(uid, symbol)
	if ErrorCode != app.ErrNone {
		h.Error(ErrorCode)
		return
	}

	response := app.AppMsg(d)
	h.Json(response)

	fmt.Println("symbol:", symbol)
}

func (*HandleCoinDetail) Destruct() {

}

func (h *Handler) getCoinDetailData(uid int, symbol string) (*app.AppCoinDetailResponse, app.AppErr) {
	conn := h.ctx.GetBaseRedis().Get()
	defer conn.Close()
	ticker, meta, err := core.GetCoinMetaAndTicker(conn, symbol)
	if err != nil {
		log.Errorf("Error: %s", err)
		return nil, app.ErrGetDataFailed
	}

	cnyRate, err := core.GetCnyRateByCoin(conn, "usd")
	if err != nil || cnyRate == "" {
		log.Errorf("Error: %s", err)
		return nil, app.ErrGetDataFailed
	}

	if ticker == nil || meta == nil {
		log.Errorf("ticker: %v, meta: %v", ticker, meta)
		return nil, app.ErrGetDataFailed
	}

	// get recommend
	recommands, err := model.ExchangeModel.GetRecommend(3)
	if err != nil {
		log.Errorf("Error: %s", err)
		return nil, app.ErrGetDataFailed
	}

	recommendExchanges := make([]app.RecommendExchangeData, 0)
	for _, r := range recommands {
		recommendExchanges = append(recommendExchanges, app.RecommendExchangeData{
			Id: 		r.Id,
			Mid: 		r.Mid,
			NameEn: 	r.NameEn,
			NameCn: 	r.NameCn,
			Slug: 		r.Slug,
			Sort: 		r.Sort,
		})
	}

	var circulatrate decimal.Decimal
	circulatingSupply, _ := decimal.NewFromString(ticker.CirculatingSupply)
	maxSupply, _ := decimal.NewFromString(meta.MaxSupply)
	if maxSupply.GreaterThan(decimal.Zero) {
		circulatrate = circulatingSupply.Div(maxSupply)
	}

	// 检查是否添加到到喜欢
	d := &app.AppCoinDetailResponse{}
	d.Mid = meta.Mid
	d.Symbol = strings.ToUpper(meta.Symbol)
	d.NameCn = meta.NameCn
	d.NameEn = meta.NameEn
	d.Logo = util.ImageUrl(h.ctx.GetImgUrl(), meta.Logo)
	d.PriceUsd = ticker.Close
	d.PriceCny = util.GetUsdToCny(ticker.Close, cnyRate)
	d.Percent = ticker.Percent
	d.Volume24h = ticker.Volume
	d.Amount24hUsd = ticker.Amount
	d.Amount24hCny = util.GetUsdToCny(ticker.Amount, cnyRate)
	d.MarketValueUsd = ticker.MarketValue
	d.MarketValueCny = util.GetUsdToCny(ticker.MarketValue, cnyRate)
	d.Description = meta.Description
	d.Website = meta.Website
	d.DateAdded = meta.DateAdded
	d.TotalSupply = meta.MaxSupply
	d.CirculatingSupply = ticker.CirculatingSupply
	d.TurnoverRate = ticker.TurnoverRate
	d.CirculatingRate = circulatrate.StringFixedBank(4)
	d.Like = h.isLiked(uid, meta.Id)
	d.Country = meta.Country
	d.NumExchange = ticker.NumExchange
	d.Recommend = recommendExchanges
	return d, app.ErrNone
}

// 是否添加该币种到关注
func (h *Handler) isLiked(uid int, id int) bool {
	if uid == 0 {
		return false
	}
	has, err := model.CoinLikeModel.CheckHasUserLiked(uid, id)
	if err != nil {
		log.Errorf("Error: %s", err)
	}
	return has
}